import { createSlice, PayloadAction } from '@reduxjs/toolkit'
import { LoginForm, fetchLogin } from '@/apis/login-logout'
import { Toast } from 'antd-mobile'
import { AxiosError } from 'axios'
import { ResType } from '@/apis'
import { storage } from '@/utils'
import { KEY_REFRESH_TOKEN, KEY_TOKEN } from '@/config/constant'

// 为 slice state 定义一个类型
interface UserState {
  userInfo: null | object
  token: string
  refresh_token: string
}

const initialState: UserState = {
  userInfo: null,
  // 提取本地token到全局
  token: storage.getItem(KEY_TOKEN) || '',
  refresh_token: storage.getItem(KEY_REFRESH_TOKEN) || ''
}

type SetTokenPayload = {
  token: string
  refresh_token: string
}

const userStore = createSlice({
  name: 'user',
  // 初始数据
  initialState,
  // 修改数据的同步方法
  reducers: {
    // 使用 PayloadAction 类型声明 `action.payload` 的内容
    setToken(state, action: PayloadAction<SetTokenPayload>) {
      const { token, refresh_token } = action.payload
      state.token = token
      state.refresh_token = refresh_token
      // 保存token到本地存储
      storage.setItem(KEY_TOKEN, token)
      storage.setItem(KEY_REFRESH_TOKEN, refresh_token)
    }
  }
})

// 解构出actionCreater函数
const { setToken } = userStore.actions

// 异步actionCreater函数
/**
 * 用户登录
 * @returns
 */
const login = (data: LoginForm, successCallback?: () => void) => {
  return async (
    dispatch: (arg0: {
      payload: SetTokenPayload
      type: 'user/setToken'
    }) => void
  ) => {
    try {
      const res = await fetchLogin(data)
      dispatch(setToken(res.data))
      Toast.show('登录成功！')
      successCallback?.()
    } catch (e) {
      const error = e as AxiosError<ResType<null>>
      // Toast.show('登录失败，请检查验证码是否正确，网络是否异常！')
      // console.log(error)
      Toast.show(
        error.response?.data.message ||
          '登录失败，请检查验证码是否正确，网络是否异常！'
      )
    }
  }
}

// 以按需导出的方式导出actionCreater函数
export { setToken, login }

// 以默认导出的方式导出reducer函数
const userReducer = userStore.reducer
export default userReducer
